package com.cactusoftware.socketandroid;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SocketAndroid extends Activity
{
	EditText editText;
	Button buttonBaglan;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_socket_android);		

		editText = (EditText)findViewById(R.id.editText1);
		buttonBaglan = (Button)findViewById(R.id.baglanbutton);

		
		buttonBaglan.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				
				new Thread(new Runnable()
				{
					SocketClient socketClient = null;
					
					@Override
					public void run()
					{
						
						try
						{
							socketClient = new SocketClient();
							runOnUiThread(new Runnable()
							{
								
								@Override
								public void run()
								{
									editText.setText(editText.getText() + "\n" + socketClient.getMessage() + "\n");									
								}
							});
						} catch (UnknownHostException e)
						{
							Toast.makeText(getApplicationContext(), "Socket sorunu! Host bulunamadi!", Toast.LENGTH_LONG).show();
							e.printStackTrace();
						} catch (IOException e)
						{
							Toast.makeText(getApplicationContext(), "Socket sorunu! IO hatasi!", Toast.LENGTH_LONG).show();
							e.printStackTrace();
						} catch (ClassNotFoundException e)
						{
							Toast.makeText(getApplicationContext(), "Socket sorunu! Mesaj sorunu!", Toast.LENGTH_LONG).show();
							e.printStackTrace();
						}catch(NullPointerException e){
							Toast.makeText(getApplicationContext(), "Socket sorunu!", Toast.LENGTH_LONG).show();
							e.printStackTrace();
						}
						
					}
				}).start();
				
				
			}
		});
				
	}

	@Override	
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_socket_android, menu);
		return true;
	}

	class SocketClient
	{
		public static final int portNumber = 3657;
		public static final String conAdd = "bgserv.no-ip.org";
		
		private String message = "";
		
		public SocketClient() throws UnknownHostException, IOException, ClassNotFoundException
		{
			Socket sock = new Socket(conAdd, portNumber);
			ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
			this.message = (String)ois.readObject();
		}
		
		public String getMessage()
		{return this.message;}
	}
	
	
}

